Strip `rust-` and `-rs` affixes in `cargo new`
authorChris Wong <lambda.fairy@gmail.com>
Mon, 20 Apr 2015 00:16:29 +0000 (12:16 +1200)
committerChris Wong <lambda.fairy@gmail.com>
Mon, 20 Apr 2015 23:13:45 +0000 (11:13 +1200)
Closes #1532

src/cargo/ops/cargo_new.rs

index 0b6862fef93df18b88fbb5b98857bdf995bb4a30..9544b52434ea0caf40d5d77060ead94b7261939f 100644 (file)
@@ -50,6 +50,12 @@ pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> {
         human(&format!("cannot create a project with a non-unicode name: {:?}",
                        path.file_name().unwrap()))
     }));
+    let name =
+        if opts.bin {
+            name
+        } else {
+            strip_rust_affixes(name)
+        };
     for c in name.chars() {
         if c.is_alphanumeric() { continue }
         if c == '_' || c == '-' { continue }
@@ -62,6 +68,20 @@ pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> {
     })
 }
 
+fn strip_rust_affixes(name: &str) -> &str {
+    for &prefix in &["rust-", "rust_", "rs-", "rs_"] {
+        if name.starts_with(prefix) {
+            return &name[prefix.len()..];
+        }
+    }
+    for &suffix in &["-rust", "_rust", "-rs", "_rs"] {
+        if name.ends_with(suffix) {
+            return &name[..name.len()-suffix.len()];
+        }
+    }
+    name
+}
+
 fn existing_vcs_repo(path: &Path) -> bool {
     GitRepo::discover(path).is_ok() || HgRepo::discover(path).is_ok()
 }
@@ -182,3 +202,20 @@ fn global_config(config: &Config) -> CargoResult<CargoNewConfig> {
         version_control: vcs,
     })
 }
+
+#[cfg(test)]
+mod tests {
+    use super::strip_rust_affixes;
+
+    #[test]
+    fn affixes_stripped() {
+        assert_eq!(strip_rust_affixes("rust-foo"), "foo");
+        assert_eq!(strip_rust_affixes("foo-rs"), "foo");
+        assert_eq!(strip_rust_affixes("rs_foo"), "foo");
+        // Only one affix is stripped
+        assert_eq!(strip_rust_affixes("rs-foo-rs"), "foo-rs");
+        assert_eq!(strip_rust_affixes("foo-rs-rs"), "foo-rs");
+        // It shouldn't touch the middle
+        assert_eq!(strip_rust_affixes("some-rust-crate"), "some-rust-crate");
+    }
+}